import {Component, ElementRef, ViewChild} from '@angular/core';
import {PageVoService} from '../../service/page-vo.service';
import {ActivatedRoute, Router} from '@angular/router';
import {DocService} from '../../service/doc.service';
import {TpHttpService} from '../../service/tp-http.service';
import {PageVo} from '../../entity/page-vo';
import {LinkDto} from '../../entity/link-dto';
import {MessageService} from '../../service/message.service';
import {BaseApiComponent} from '../page-api/base-api.component';
import {formatDate} from '@angular/common';
import {DocLog} from '../../entity/doc-log';
import {AlertMessage} from '../../entity/alert-message';
import {HttpErrorResponse} from '@angular/common/http';

@Component({
    selector: 'app-page-history',
    templateUrl: './page-history.component.html',
    styleUrls: ['./page-history.component.css']
})
export class PageHistoryComponent extends BaseApiComponent {
    /**
     * 历史记录
     */
    docs: DocLog[];

    /**
     * 当前分页数
     * @type {number}
     */
    pageNo = 1;

    /**
     * 每页记录数
     * @type {number}
     */
    pageSize = 50;

    /**
     * 是否有下一页
     * @type {boolean}
     */
    hasNextPage = false;

    selectAll = false;

    loaddingMessage = '正在加载，请稍候...';

    isOwner = false;

    constructor(protected pageVoService: PageVoService,
                protected activatedRoute: ActivatedRoute,
                protected router: Router,
                protected docService: DocService,
                private httpService: TpHttpService,
                protected messageService: MessageService) {
        super(pageVoService, activatedRoute, router, docService, messageService);
    }

    protected onApiReady() {
        this.isOwner = this.docService.isCurrentDocOwner();
        let pageNo = 1;

        const pageNoStr = this.activatedRoute.snapshot.queryParamMap.get('p');
        if (pageNoStr) {
            pageNo = parseInt(pageNoStr, 10);
        }
        if (pageNo < 1) {
            pageNo = 1;
        }
        this.loadPage(pageNo);
    }

    toggleSelectAll() {
        this.selectAll = !this.selectAll;
        if (!this.docs) {
            return;
        }
        this.docs.filter(doc => !this.isNewest(doc)).forEach(doc => doc.checked = this.selectAll);
    }

    loadPage(pageNo: number) {
        const body = {
            'docId': this.docId,
            'pageNo': pageNo,
            'pageSize': this.pageSize
        };
        this.pageNo = pageNo;
        this.loaddingMessage = '正在加载，请稍候...';
        this.httpService.post('/api/doc/history', JSON.stringify(body)).subscribe((resp: DocLog[]) => {
            this.docs = resp;
            this.hasNextPage = this.docs.length === this.pageSize;
        }, (errorResp: HttpErrorResponse) => {
            this.loaddingMessage = '加载失败：' + errorResp.error.message;
            this.messageService.add(<AlertMessage>{
                id: 'history_load_error',
                type: 'error',
                html: `<strong>系统错误：</strong>${errorResp.error.message}`,
                time: 8
            });
        });
    }

    protected getActiveMenuId() {
        return 'history';
    }

    getVersion(docVersion: number): string {
        return formatDate(docVersion, 'yyyy-MM-dd HH:mm', this.LOCALE);
    }

    setPageVo(basePageVo: PageVo) {
        basePageVo.crumbs.push(<LinkDto> {
            text: '历史文档',
            frontIcon: 'history'
        });
    }

    getRouterLink(doc: DocLog) {
        const link = ['/doc', doc.docId];
        if (this.isNewest(doc)) {
            return link;
        }
        link.push('v', doc.docVersion.toString());
        return link;
    }

    isNewest(doc: DocLog): boolean {
        return this.doc.artifact.docVersion <= doc.docVersion;
    }

    deleteDocLogs() {
        const forDelDocs = this.docs.filter(doc => doc.checked)
            .forEach(doc => this.deleteDocLog(doc));
        this.selectAll = false;
    }

    deleteDocLog(doc: DocLog) {
        this.httpService.del('/api/doc/' + doc.docId + '/?version=' + doc.docVersion).subscribe(result => {
            if (result !== '成功') {
                this.messageService.add(<AlertMessage>{
                    id: 'del_doc_er_' + doc.id,
                    type: 'error',
                    html: `<strong>删除历史文档操作失败：</strong>${result}`
                });
            } else {
                // 删除成功
                this.messageService.add(<AlertMessage>{
                    id: 'del_doc_' + doc.id,
                    type: 'success',
                    html: `<strong>删除历史文档：</strong>v${formatDate(doc.docVersion, 'yyyy-MM-dd HH:mm', this.LOCALE)}`,
                    time: 3
                });
                this.docs.forEach((d, index) => {
                    if (d === doc) {
                        this.docs.splice(index, 1);
                    }
                });
                if ((this.pageNo === 1 && this.docs.length <= 1) || (this.pageNo > 1 && this.docs.length === 0)) {
                    // 重新加载
                    if (this.hasNextPage) {
                        // 刷新当前页
                        this.loadPage(this.pageNo);
                    } else if (this.pageNo > 1) {
                        this.loadPage(this.pageNo - 1);
                    }
                }
            }
        });
    }

    hasChecked() {
        if (!this.docs) {
            return false;
        }
        return this.docs.filter(doc => doc.checked).length > 0;
    }
}
